﻿using System;
using System.Linq;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Collections;

namespace Evpo.ContactData.Data
{
    internal class ProcedureOutputReader : StatementExecutionBase
    {
        internal ProcedureOutputReader(Connection conn, string procedureName) :
            base(conn, procedureName, Enumerable.Empty<SqlParameter>())
        {
        }

        internal ProcedureOutputReader(Connection conn, string procedureName, IEnumerable<SqlParameter> parameters) :
            base(conn, procedureName, parameters) { }
        

        #region Fields

        #endregion

        #region Properties

        private SqlDataReader Reader
        {
            get;
            set;
        }
        #endregion

        #region Methods

        internal bool IsDBNull(string columnName)
        {
            int ordinal = Reader.GetOrdinal(columnName);

            return Reader.IsDBNull(ordinal);
        }

        internal DateTime GetDateTime(string columnName)
        {
            return Reader.GetDateTime(Reader.GetOrdinal(columnName));
        }

        internal int GetID(string columnName)
        {
            return Reader.GetInt32(Reader.GetOrdinal(columnName));
        }

        internal string GetString(string columnName)
        {
            int ordinal = Reader.GetOrdinal(columnName);
            
            if (Reader.IsDBNull(ordinal))
                return null;

            return Reader.GetString(ordinal);
        }

        internal bool GetBoolean(string columnName)
        {
            return Reader.GetBoolean(Reader.GetOrdinal(columnName));
        }

        internal SqlDataReader CreateReader()
        {
            if (Reader != null)
                throw new InvalidOperationException("Reader is already created");

            Connection.Open();
            Reader = Command.ExecuteReader();
            return Reader;
        }

        #endregion

        #region IDisposable
        public override void Dispose()
        {
            base.Dispose();
            if (Reader != null)
            {
                Reader.Close();
                Reader.Dispose();
            }
        }
        #endregion
    }
}
